import os

from django.http import JsonResponse
from django.shortcuts import render
import jieba
from django.views.decorators.csrf import csrf_exempt

from views import textRank
from .models import Completion
from service.models import personalQB


@csrf_exempt
def showFileGQ(request):  # 展示老师问题生成页面
    return render(request, '1tianKong.html')


@csrf_exempt
def showAll(request):  # 展示老师查看题库页面
    obj = Completion.objects.all()
    return render(request, '1tiKu.html', {'mayanswer': obj})


@csrf_exempt
def show_stu_completion_answer(request):  # 展示学生回答问题页面
    account = request.session.get('account')
    try:
        completion = Completion.objects.raw('SELECT * FROM `completion_completion` '
                                            'where completion_completion.ID not in'
                                            '( SELECT completion_completion.ID '
                                            'FROM `completion_completion`,`service_personalqb` '
                                            'WHERE(completion_completion.ID = service_personalqb.questionID '
                                            'and service_personalqb.TypeID = 2 '
                                            'and service_personalqb.Account = \'%s\') )' % format(account))

        return render(request, 'stu_completion_answer.html', {'completion': completion})
    except:
        completion is None
        return render(request, 'stu_completion_answer.html', {'completion': completion})


@csrf_exempt
def show_stu_completion_wrong(request):  # 展示学生查看错题页面
    account = request.session.get('account')
    wrongCompletion = personalQB.objects.filter(TypeID=2, statusID=0, Account=account)
    allAnsweredCompletion = personalQB.objects.filter(TypeID=2, Account=account)
    return render(request, 'stu_completion_wrong.html', {'wrong': wrongCompletion,
                                                         'allAnsweredCompletion': allAnsweredCompletion})


@csrf_exempt
def fileQg(request):  # 生成的问题存到数据库中
    obj = request.FILES.get('file')  # 获取前端文件
    QGnum = int(request.POST.get('num'))  # 生成问题个数
    f = open(os.path.join('media', obj.name), 'wb+')  # 写入文件
    for i in obj:
        f.write(i)
    f.close()
    fileName = './media/' + obj.name
    keywords, keySentences = textRank(fileName, QGnum)  # 对文件提取关键词和关键句
    Dict = './static/dict.txt'
    for org in keySentences:
        org_con = org.split("，", 1)
        if len(org_con[0]) < 5:
            org = org_con[1]
        if len(org) > 5:
            if org[0] == '(' and org[2] == ')' or org[0] == '（' and org[2] == '）':
                org = org[3:len(org)]
        words = jieba.lcut(org)  # 分词
        num_dict = ['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩']
        for i in num_dict:
            if org[0] == i:
                org = org[1:len(org)]
    with open(Dict, 'r', encoding='utf-8') as fileObject:  # 向关键词库导入专属名词
        terminology = fileObject.read().splitlines()
        for k in terminology:
            if k not in keywords:
                keywords.append(k)
    mayAnswer = []
    jieba.load_userdict(keywords)
    for org in keySentences:
        words = jieba.lcut(org)  # 分词
        for word in words:  # 遍历分词结果
            if word in keywords:  # 如果分出的词在关键词里
                n = 0
                for i in words:  # 对原句中关键词计数
                    if word == i:
                        n += 1
                if n == 1:  # 若只有一个关键字
                    question = org.replace(word, "________")  # 关键词替换
                    count = Completion.objects.count()  # 数据库个数计数
                    answerObject = Completion(org=org, ID=count + 1, question=question,
                                              answer=word)  # 构建题目对象
                    # if not Completion.objects.filter(org=answerObject.org,
                    #                                  question=answerObject.question):  # 如果数据库中没有此题目(不存在返回True)
                    #     answerObject.save()  # 保存到数据库
                    mayAnswer.append(answerObject)  # 将题目对象加入到列表中
                else:
                    continue
    os.remove(os.path.join('media', obj.name))  # 删除缓存文件
    return render(request, '1tianKong.html', {'mayanswer': mayAnswer})


@csrf_exempt
def saveData(request):
    res = {}
    if request.method == 'POST':
        data = request.POST.get('qg')
        init = data.split('/')  # 第一次被分割
        init = init[:-1]
        try:
            for fss in init:  # 遍历
                sss = fss.split('|')  # 切分
                org = sss[0]  # 原句
                question = sss[1]  # 问题
                answer = sss[2]  # 答案
                count = Completion.objects.count()  # 数据库个数计数
                answerObject = Completion(org=org, ID=count + 1, question=question,
                                          answer=answer)  # 构建题目对象
                if not Completion.objects.filter(org=answerObject.org,
                                                 question=answerObject.question):  # 如果数据库中没有此题目(不存在返回True)
                    answerObject.save()  # 保存到数据库
            res['status'] = 100
            return JsonResponse(res)
        except:
            res['status'] = 501
            return JsonResponse(res)
    else:
        res['status'] = 500
        return JsonResponse(res)


def cutWord(sentence, word_dic):
    # Dict = '../static/dict.txt'
    # with open(Dict, 'r', encoding='utf-8') as fileObject:  # 导入专属名词
    #     terminology = fileObject.readlines()
    #     for k in terminology:
    #         if k not in word_dic:
    #             word_dic.append(k)
    word_length_list = [len(word) for word in word_dic]  # 字典里的词的长度
    max_length = max(word_length_list)  # 词的最大长度
    word_length = len(sentence)  # 句子长度
    cut_word_list = []  # 创建一个列表，存放已经分好的结果
    while word_length > 0:  # 句子长度大于0
        max_cut_length = min(max_length, word_length)  # 求最大切割长度
        subsentence = sentence[0:max_cut_length]
        while max_cut_length > 0:
            if subsentence in word_dic:  # 在字典中找词
                cut_word_list.append(subsentence)
                break
            if max_cut_length == 1:
                cut_word_list.append(subsentence)
                break
            else:
                max_cut_length = max_cut_length - 1
                subsentence = subsentence[0:max_cut_length]
        sentence = sentence[max_cut_length:]

        word_length = word_length - max_cut_length

    return cut_word_list
